package com.xiaouyudeguang.common.config;

import com.zlyx.easy.security.authentication.configurer.AbstractSecurityConfigurer;
import com.zlyx.easy.security.authentication.filter.RequestAuthorizationTokenFilter;
import com.zlyx.easy.security.tokenstore.redis.annotation.EnableRedisTokenStore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

@Data
@Order(1)
@EnableWebSecurity
@EnableRedisTokenStore
@EqualsAndHashCode(callSuper = false)
public class OAuthSecurityAdaptConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfigurerAdapter.class);

    @Autowired
    private List<AbstractSecurityConfigurer> adapters;

    @Autowired
    private RequestAuthorizationTokenFilter authenticationTokenFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and()
                .formLogin().and().logout().and().authorizeRequests().anyRequest().permitAll();
        if (adapters != null) {
            adapters.forEach(adapter -> {
                try {
                    http.apply(adapter);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            });
        }
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
